package com.aoxiang.zbox.config.filter;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class CorsFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String origin = request.getHeader("Origin");

        // 允许指定的 Origin 访问
        if (origin != null && !"null".equals(origin)) {
            response.setHeader("Access-Control-Allow-Origin", origin);  // 设置动态 Origin
        } else {
            response.setHeader("Access-Control-Allow-Origin", "*");  // 允许任何来源
        }

        // 允许带凭证的请求（如果不需要，设为 false 或删除）
        response.setHeader("Access-Control-Allow-Credentials", "true");

        // 允许的请求方法
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT, OPTIONS");

        // 允许的请求头（必须包含 Authorization）
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");

        // 预检请求的缓存时间（1小时）
        response.setHeader("Access-Control-Max-Age", "3600");

        // 处理 OPTIONS 预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        filterChain.doFilter(request, response);
    }

}
